<template>
  <div>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="问题类型">
        <el-select v-model="form.type_id" placeholder="请选择问题类型">
          <el-option
            v-for="(e, index) in types"
            :key="index"
            :label="e.type"
            :value="e.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="问题题干">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="答案1">
        <el-input v-model="form.option1"></el-input>
      </el-form-item>
      <el-form-item label="答案2">
        <el-input v-model="form.option2"></el-input>
      </el-form-item>
      <el-form-item label="答案3">
        <el-input v-model="form.option3"></el-input>
      </el-form-item>
      <el-form-item label="答案4">
        <el-input v-model="form.option4"></el-input>
      </el-form-item>
      <el-form-item label="正确答案">
        <el-radio-group v-model="answer">
          <el-radio label="答案1"></el-radio>
          <el-radio label="答案2"></el-radio>
          <el-radio label="答案3"></el-radio>
          <el-radio label="答案4"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import qs from "qs";
export default {
  data() {
    return {
      form: {
        title: "",
        option1: "",
        option2: "",
        option3: "",
        option4: "",
        type_id: "",
        answer: "",
      },
      answer: "",
      types: [],
    };
  },
  watch: {
    answer(newValue) {
      switch (newValue) {
        case "答案1":
          this.form.answer = this.form.option1;
          break;
        case "答案2":
          this.form.answer = this.form.option2;
          break;
        case "答案3":
          this.form.answer = this.form.option3;
          break;
        case "答案4":
          this.form.answer = this.form.option4;
          break;
      }
    },
  },
  methods: {
    onSubmit() {
      if (this.form.answer.trim()) {
        let data = qs.stringify(this.form);
        this.axios.post("/addSubject", data).then((results) => {
          if (results.data) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.form = {
              title: "",
              option1: "",
              option2: "",
              option3: "",
              option4: "",
              type_id: "",
              answer: "",
            };
            this.answer = '';
          } else {
            this.$message.error("添加失败");
          }
        });
      }
    },
  },
  created() {
    this.axios.get("/getType").then((results) => {
      this.types = results.data;
    });
  },
};
</script>

<style scoped>
</style>
